/**
 * 
 */
package org.paybiz.core.payplatform.bill99.service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.paybiz.constant.PayConstant;
import org.paybiz.constant.ErrorConstant;
import org.paybiz.core.payplatform.bill99.constant.Bill99Constant;
import org.paybiz.core.payplatform.bill99.entity.Ivr;
import org.paybiz.core.payplatform.bill99.entity.ResultVO;
import org.paybiz.core.payplatform.bill99.entity.TransInfo;
import org.paybiz.core.payplatform.bill99.util.ParseUtil;

/**
 * Ivr语音支付处理类
 * 
 * @author nassir wen
 * @data 2012-5-15 上午11:59:14
 * @version V2.5
 * @Company: MSD.
 * @Copyright Copyright (c) 2012
 */
public class IvrServiceHandler {

    private final static Log logger = LogFactory
            .getLog(IvrServiceHandler.class);

    /**
     * 语音支付数据发送
     * 
     * @param ivr
     * @throws Exception
     */
    public static ResultVO ivrSend(Ivr ivr) {
        if (logger.isInfoEnabled()) {
            logger.info("语音支付数据发送...");
            logger.info("订单号：" + ivr.getExternalRefNumber() + " "
                    + ivr.getCardHolderName() + " 支付: " + ivr.getAmount() + " 元");
        }
        ResultVO result = new ResultVO();

        // 设置提交TR1的XML数据的地址
        TransInfo transInfo = new TransInfo();
        // 返回组合前和返回TR2后的第一个标志字段
        transInfo.setRecordeText_1("TxnMsgContent");
        // 返回TR2后的错误标志字段
        transInfo.setRecordeText_2("ErrorMsgContent");
        // 设置最后的解析方式
        transInfo.setFLAG(true);
        // 获取发送xml
        String reqXml = PostTr1ProcessorHandler
                .createSendTR1XML(ivr, transInfo);
        // 得到服务端返回
        HashMap<Object, Object> respXml = null;
        try {
            logger.info("语音支付发送 TR1信息：" + reqXml);
            InputStream is = PostTr1ProcessorHandler.post(reqXml,
                    Bill99Constant.IVR_PURCHASE);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] receiveBuffer = new byte[2048];
            int readBytesSize = is.read(receiveBuffer);
            while (readBytesSize != -1) {
                bos.write(receiveBuffer, 0, readBytesSize);
                readBytesSize = is.read(receiveBuffer);
            }
            String reqData = new String(bos.toByteArray(), "UTF-8");
            logger.info("语音支付服务器返回 TR2信息：" + reqData);
            if (is != null) {
                // 给解析XML的函数传递快钱返回的XML数据流
                respXml = ParseUtil.parseXML(reqData, transInfo);
            }
            if (respXml != null) {
                String responseCode = (String) respXml.get("responseCode");
                // 记录此编号，用于查询交易报文和退货
                String refNumber = (String) respXml.get("refNumber");
                // 如果TR2获取的应答码responseCode的值为CO时，交易正在处理中，银行电话正在连接中
                if (StringUtils
                        .equals(Bill99Constant.IVR_PROCESS, responseCode)
                        || StringUtils.equals(Bill99Constant.IVR_SUC,
                                responseCode)) {
                    result.setResultCode(PayConstant.RESULT_SUCCESS + "");
                    ivr.setRefNumber(refNumber);
                } else {
                    String responseTextMessage = (String) respXml
                            .get("responseTextMessage");
                    result.setResultCode(ErrorConstant.IVR_INFORMATION_ERROR);
                    if (StringUtils.isNotEmpty(responseTextMessage)) {
                        result.setErrMsg(responseTextMessage);
                        logger.error(responseTextMessage);
                    } else {
                        result.setErrMsg(ErrorConstant.IVR_INFORMATION_ERROR_VALUE);
                        logger.error(ErrorConstant.IVR_INFORMATION_ERROR
                                + " errCode: " + respXml.get("errorCode")
                                + " errMsg: " + respXml.get("errorMessage"));
                    }
                }
            } else {
                result.setResultCode(PayConstant.RESULT_FAIL + "");
                result.setErrMsg("银行返回信息为空");
            }
        } catch (Exception e) {
            logger.error("发送TR1失败，"
                    + ErrorConstant.IVR_BANK_SERVICE_ERROR_VALUE, e);
            result.setResultCode(ErrorConstant.IVR_BANK_SERVICE_ERROR);
            result.setErrMsg(ErrorConstant.IVR_BANK_SERVICE_ERROR_VALUE);
        }
        return result;
    }

    /**
     * 查询
     */
    public static void ivrQuery() throws Exception {

    }

    /**
     * 退款
     */
    public static void ivrRefund() throws Exception {

    }
}
